package com.yzy.security;

import com.yzy.domain.entity.annotation.PassToken;
import com.yzy.domain.entity.system.Account;
import com.yzy.domain.entity.annotation.CheckPermission;
import com.yzy.exception.GlobalExceptionMessage;
import com.yzy.exception.VisionException;
import com.yzy.properties.GlobalProperties;
import com.yzy.service.AccountService;
import com.yzy.service.RolePermissionService;
import com.yzy.util.algorithm.JWTUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.net.MalformedURLException;

public class AuthenticationInterceptor implements HandlerInterceptor {

    @Resource
    private GlobalProperties globalProperties;

    @Resource
    private RolePermissionService permissionService;

    @Resource
    private AccountService accountService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws MalformedURLException {
        String token = request.getHeader(globalProperties.getTokenHeader());
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        //检查是否有PassToken注释
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }

        // 验证token
        if (StringUtils.isBlank(token)) {
            throw new VisionException(HttpStatus.UNAUTHORIZED, GlobalExceptionMessage.TOKEN_INVALID_ON_REQUEST_HEADER);
        }

        JWTUtils.verify(token);

        Account account = accountService.getAccountFromRequest(request);
        if (null == account) {
            throw new VisionException(HttpStatus.UNAUTHORIZED, "请登录后再进行操作!");
        }

        if (account.getDisabled()) {
            throw new VisionException(HttpStatus.UNAUTHORIZED, "该用户已被禁用，请联系管理员!");
        }

        // 检查是否有CheckPermission注释
        if (method.isAnnotationPresent(CheckPermission.class)) {
            CheckPermission checkPermission = method.getAnnotation(CheckPermission.class);
            permissionService.checkPermission(checkPermission.values(), account.getId());
        }

        return true;
    }
}